
import {get_User_ID} from '@/utils';
import {reqCartList, reqChangeShopCart, reqChangeSkuSel, reqDelsku} from '@/api'

export default {
    namespaced: true,
    actions: {
        //获取购物车信息
        async getCartList({commit}) {
            let result = await reqCartList();
            if (result.code == 200) {
                commit('GETCARTLIST', result.data);
            }else Promise.reject('faile');
        },
        //改变商品数量
        async getChangeShopCart({commit}, {skuId, skuNum}) {
            let result = await reqChangeShopCart(skuId,skuNum);
            if (result.code == 200) {
                return 'ok';
            }else Promise.reject('faile');
        },
        // 改变商品选中状态
        async changeSkuSel({commit},{skuId, isChecked}) {
            let result = await reqChangeSkuSel(skuId, isChecked);
            if(result.code == 200) {
                return 'ok';
            }else Promise.reject('faile');
        },
        // 删除购物车某个商品
        async delSku({commit}, skuId) {
            let result = await reqDelsku(skuId);
            if (result.code == 200) {
                return 'ok';
            }else Promise.reject('faile');
        },
        getChangeAllSkuSel({dispatch, getters}, isChecked) {
            let arr = [];
            getters.cartInfoList.forEach(it => {
                arr.push(
                    dispatch('changeSkuSel', {skuId:it.skuId, isChecked})
                );
            });
            return Promise.all(arr);
        },
        // 删除所有选中商品
        delAllSelSku({getters, dispatch}) {
            let arr = [];
            getters.cartInfoList.forEach(it=> {
                if (it.isChecked == 1) {
                    arr.push(
                        dispatch('delSku', it.skuId)
                    )
                }
            });
            return Promise.all(arr);
        }
    },
    mutations: {
        GETCARTLIST(state, data) {
            state.cartList = data || [];
        },
    },
    state: {
        uuidToken: get_User_ID(),
        cartList:[],
    },
    getters: {
        cartInfoList(state) {
            return state.cartList[0] ? state.cartList[0].cartInfoList || [] : [];
        }
    }
}